package com.wash.framework.page;

import com.wash.framework.utils.ConfigUtil;
import com.wash.framework.utils.StringUtils;
import org.apache.ibatis.session.RowBounds;

public class PageUtil
{
  public static final int FIRST_PAGE = 1;
  public static final int DEFAULT_PAGE_SIZE = 10;

  public static RowBounds get(Integer pageNo, Integer pageSize)
  {
    if ((pageNo == null) || (pageNo.intValue() < 0)) {
      pageNo = Integer.valueOf(1);
    }
    if ((pageSize == null) || (pageSize.intValue() <= 0)) {
      pageSize = Integer.valueOf(10);
    }

    return getRowBounds(pageNo, pageSize);
  }

  private static int getFirst(int pageNo, int pageSize)
  {
    return (pageNo - 1) * pageSize;
  }

  private static int getLast(int first, int pageSize)
  {
    return first + pageSize;
  }

  public static int begin(int pageNo, int pageSize)
  {
    return getFirst(pageNo, pageSize);
  }

  public static int end(int pageNo, int pageSize)
  {
    return getLast(getFirst(pageNo, pageSize), pageSize);
  }

  private static int getTotalPage(int totalRow, int pageSize)
  {
    if (pageSize != 0) {
      if (totalRow % pageSize != 0) {
        return totalRow / pageSize + 1;
      }
      return totalRow / pageSize;
    }

    return 0;
  }

  public static int validateRequestPage(String requestPage)
  {
    int currentPage = 1;
    if (!StringUtils.isEmpty(requestPage)) {
      try {
        currentPage = Integer.parseInt(requestPage);
      } catch (Exception e) {
        currentPage = 1;
      }
    }
    return currentPage;
  }

  private static int validateTotalPage(int currentPage, int totalPage)
  {
    if (currentPage > totalPage) {
      currentPage = totalPage;
    }
    if (currentPage < 1) {
      currentPage = 1;
    }

    return currentPage;
  }

  private static RowBounds getRowBounds(Integer pageNo, Integer pageSize)
  {
    String dataBase = ConfigUtil.getConfig("db.database", "mysql");

    int first = 0;
    int last = 0;

    if ("mysql".equals(dataBase))
    {
      first = getFirst(pageNo.intValue(), pageSize.intValue());
      last = pageSize.intValue();
    }
    else if ("oracle".equals(dataBase))
    {
      first = getFirst(pageNo.intValue(), pageSize.intValue());
      last = getLast(first, pageSize.intValue());
    }
    return new RowBounds(first, last);
  }

  public static PageObject makePageObject(String myCurrentPage, int totalRow, int pageSize)
  {
    int currentPage = validateRequestPage(myCurrentPage);

    int totalPage = getTotalPage(totalRow, pageSize);

    currentPage = validateTotalPage(currentPage, totalPage);
    PageObject pageObject = new PageObject();
    pageObject.setCurrentPage(currentPage);
    pageObject.setTotalPage(totalPage);
    pageObject.setPerPage(pageSize);
    pageObject.setTotalRow(totalRow);
    return pageObject;
  }
}